package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.utils.R;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.User;
import com.bwie.mapper.UserMapper;
import com.bwie.service.UserService;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: 秋晚
 * @Date:  2025/7/7 11:00
 * @Description: 
 **/

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired
    UserMapper userMapper;

    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public R login(User user) {
        //创建条件
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        //判断
        if(StringUtils.isNotEmpty(user.getUsername())){
            wrapper.eq(User::getUsername,user.getUsername());
        }
        if(StringUtils.isNotEmpty(user.getPhone())){
            //手机号正则校验
            Pattern compile = Pattern.compile("^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$");
            Matcher matcher = compile.matcher(user.getPhone());
            if(!matcher.matches()){
                return R.ERROR(400,"手机号格式错误!");
            }
            wrapper.or().eq(User::getPhone,user.getPhone());
        }
        if(StringUtils.isNotEmpty(user.getEmail())){
            wrapper.or().eq(User::getEmail,user.getEmail());
        }

        //根据条件查询
        User one = userMapper.selectOne(wrapper);
        if(ObjectUtils.isEmpty(one)){
            return R.ERROR(500,"用户不存在");
        }
        //判断密码是否正确
        if(!user.getPassword().equals(one.getPassword())){
            return R.ERROR(500,"密码错误!");
        }
        //生成token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").claim("id", one.getId()).compact();
        //存储
        redisTemplate.opsForValue().set("token-"+one.getId(),token,15, TimeUnit.MINUTES);
        //放入token
        one.setPassword(null);
        one.setToken(token);
        return R.OK(one);
    }

    @Override
    public R getAllUser() {
        List<User> users = userMapper.selectList(null);

        return R.OK(users);
    }


}
